import React, { Component } from 'react';
//
import Model from '@/models/user'
import AddUser from './AddUser'
import UpdateUser from './UpdateUser'
import { Table,Space, Button, message, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from "moment"
import '@/assets/css/userlist.css'
const { confirm } = Modal;
class Userlist extends Component {
    columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            align:"center",
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            align:"center",
        },
        {
            title: '电话',
            dataIndex: 'phone',
            key: 'phone',
            align:"center",
        },
        {
            title: '注册时间',
            key: 'create_time',
            dataIndex: 'create_time',
            align:"center",
            render:(time)=>{
                return time?moment(parseInt(time)).format('YYYY-MM-DD hh:mm:ss'):"";
            }
        },
        {
            title: '所属角色',
            key: 'role_id',
            dataIndex: 'role_id',
            align:"center",
            render: (role_id) => {
                return this.roleNames[role_id]
            }
        },
        {
            title: '操作',
            key: 'action',
            align:"center",
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => this.showModal2(record)}>修改</a>

                    <a onClick={() => this.showDeleteConfirm(record)}>删除</a>
                </Space>
            ),
        },
    ];
    state = {
        userdata: [],
        roledata: [],
        userdatalength: 1,
        current_page: 1,
        visible: false,
        visible2: false,
        confirmLoading: false,
        confirmLoading2: false,
        submitadd: false,
        submitadd2: false,
        already: false,
        //
        updateinfo: ''
    }
    render() {
        let { userdata, current_page, visible, confirmLoading, roledata, submitadd,
            visible2, confirmLoading2, submitadd2
        } = this.state
        return (
            <div>
                <div>
                    <Button type="primary" onClick={this.showModal}>创建用户</Button>
                </div>
                <hr />
                <Table columns={this.columns} dataSource={userdata} pagination={false} rowKey={(row) => row._id}
                    pagination={{ defaultPageSize: 7, onChange: this.getPage, current: current_page }} />
                <Modal
                    title="创建用户"
                    visible={visible}
                    onOk={this.handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                    destroyOnClose={true}
                >
                    <AddUser sentrole={roledata} submitadd={submitadd} />
                </Modal>
                <Modal
                    title="修改用户"
                    visible={visible2}
                    onOk={this.handleOk2}
                    confirmLoading={confirmLoading2}
                    onCancel={this.handleCancel2}
                    destroyOnClose={true}
                >
                    <UpdateUser sentrole={roledata} submitadd2={submitadd2} sentupInfo={this.state.updateinfo} />
                </Modal>
            </div>
        );
    }
    componentDidMount() {
        let { current_page } = this.state
        this.Inituserlist(current_page)
    }
    //获取用户
    Inituserlist(current_page){
        Model.userList().then(ret => {
            // console.log(ret);
            let { users, roles } = ret.data
            if (ret.status === 0) {
                this.getroleName(roles)
                this.setState(() => {
                    return {
                        userdata: users,
                        roledata: roles,
                        userdatalength: ret.data.users.length,
                        current_page
                    }
                },()=>{
                    localStorage.setItem('userlength',this.state.userdatalength)
                })
            }
            else {
                message.error('数据异常！')
            }
        })
    }
    //匹配id 找到相应角色名
    getroleName(roles) {
        // console.log(roles);
        // 根据role数组 生成包含所有角色名的对象（属性名角色id值）
        const roleNames = roles.reduce((pre, role) => {
            pre[role._id] = role.name
            return pre
        }, {})
        // 保存起来一堆的rolesName
        this.roleNames = roleNames
        // console.log(this.roleNames);
    }
    //获取当前页
    getPage = (page) => {
        // console.log('页' + page);

        this.setState(() => {
            return {
                current_page: page
            }
        })
    }
    //添加用户modal
    showModal = () => {
        this.setState(() => {
            return {
                visible: true,
            }
        })
    };

    handleOk = () => {

        this.setState({
            confirmLoading: true,
            submitadd: true,
        })
        setTimeout(() => {
            this.setState({
                confirmLoading: false,
                visible: false,
                submitadd: false,
            }, () => {
                this.Inituserlist(this.state.current_page)
            })
        }, 2000);
    };
    handleCancel = () => {
        this.setState({
            visible: false
        })
    };
    //
    //修改用户modal
    showModal2 = (data) => {
        // console.log(data);
        this.setState(() => {
            return {
                visible2: true,
                updateinfo: data
            }
        }, () => {
            // console.log(this.state.updateinfo);
            // this.setState({
            //     already:true
            // })
        })
    };

    handleOk2 = () => {

        this.setState({
            confirmLoading2: true,
            submitadd2: true,
        })
        setTimeout(() => {
            this.setState({
                confirmLoading2: false,
                visible2: false,
                submitadd2: false,
            }, () => {
                this.Inituserlist(this.state.current_page)
            })
        }, 2000);
    };

    handleCancel2 = () => {
        this.setState({
            visible2: false
        })
    };
    //删除用户
    showDeleteConfirm = (data) => {
        let _this = this
        confirm({
            title: '删除',
            icon: <ExclamationCircleOutlined />,
            content: `确定要删除${data.username}`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                let values ={}
                values['userId'] = data._id
                Model.delUser(values).then(ret => {
                    if (ret.status === 0){
                        message.success('删除成功！')
                        _this.Inituserlist(_this.state.current_page)
                    }
                    else
                        message.error("删除失败！")
                })
            },
            onCancel() {
            },
        });

    }
}

export default Userlist;
